<?php
namespace App\V3\V3_1\Services;

use App\V3\V3_1\Models\AdminAddendumModel;
use App\V3\V3_1\Models\AdminModel;
use App\V3\V3_1\Models\LogInStorageModel;
use App\V3\V3_1\Models\LogOutStorageModel;
use App\V3\V3_1\Models\OperationLogModel;
use App\V3\V3_1\Models\SerialNumberModel;
use App\V3\V3_1\Models\StorageManageModel;
use App\V3\V3_1\Models\StorageModel;
use App\V3\V3_1\Models\VipSettingModel;
use App\V3\Api\Services\DataFieldService;
use App\Helper\DBRSAUtil;
use App\V3\V3_1\Models\ModuleModel;
use App\V3\V3_1\Models\RoleSettingModel;
use App\V3\V3_1\Models\SystemConfigModel;
use App\Http\Controllers\Api\SyncDataController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;

class LoginService
{
    const SALT = 'storage';

    static public function defaultCodeLog($data, $deviceId, $minicode)
    {
        $userInfo = AdminModel::select(
            'admin.*',
            'is_vip',
        )
            ->where([
                'username' => $data['mobile'],
                'parent_id' => 0,
                'delete_flag' => 0
            ])->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.id')->first();

        if(!empty($userInfo)) {
            $userId = $userInfo['id'];//子账号(账号类型为主账号时子账号同主账号)

            $mainUserId = $userId;//主账号id
            if($userInfo['is_vip'] > 0 && $userInfo['invite_num'] < 3){
                $userInfo['invite_num'] = 3;
            }
            $result = self::common([
                'userId'=>$userId,
                'mainUserId'=>$mainUserId,
                'userType'=>0,//账号类型： 0-主 1-子
                'type'=>$data['device'],
                'is_default_code' => 1,
                'company_name' => $userInfo['company_name'],
                'out_storage_way' => $userInfo['out_storage_way'],
                'is_vip' => $userInfo['is_vip'],
                'is_sync' => $userInfo['is_sync']
            ]);

            if($result['code']) {
                return $result;
            }

            if($data['device'] == 3) {
                $roleInfo = RoleSettingModel::where('role_id', $userInfo['admin_role'])->first();

                $userFirstModuleArr = array_filter(explode(',', $roleInfo['first_module']), function($v) { return $v !== ''; });
                $userSecondModuleArr = array_filter(explode(',', $roleInfo['second_module']), function($v) { return $v !== ''; });

                $moduleInfo = self::moduleCommon($userFirstModuleArr, $userSecondModuleArr);
                $result['data']['bind_id'] = $userInfo['bind_id'];
                $result['data']['invite_num'] = $userInfo['invite_num'];
                $result['data']['invite_info'] = AdminService::inviteInfo($userInfo['id']);
                $result['data']['is_bind_openid'] = empty($userInfo['openid'])?0:1;
                $result['data']['is_vip'] = $userInfo['is_vip'];
                $result['data']['nickname'] = $userInfo['nickname'];
                $result['data']['out_storage_way'] = $userInfo['out_storage_way'];
                $result['data']['module_info'] = $moduleInfo;
            }

            $result['data']['parent_id'] = $userInfo['id'];
            $result['data']['is_sync'] = $userInfo['is_sync'];


            if(!empty($deviceId) && $deviceId != 'null' && $deviceId != null) {
                AdminModel::where('id', $userId)->update([
                    'device_id' => $deviceId
                ]);
            }

//            if($userInfo['is_sync'] == 0) {
//                SyncDataController::syncMaterielCost($mainUserId, $userInfo['batch_title']);
//
//                AdminModel::where('id', $mainUserId)->update(['is_sync' => 1]);
//            }

            $adminArray = json_decode(Redis::get('admin_array'), true);

            //字段权限列表
            $result['data']['field_list'] = DataFieldService::distinguishPermissionList($userInfo['id']);

            $key = array_search($userId, empty($adminArray)?[]:$adminArray);

            //主账号权限发生变动后重新登录取消权限不足的提示
            if($key !== false) {
                unset($adminArray[$key]);
                Redis::SETEX('admin_array', 86400*15, json_encode($adminArray));
            }

            $result['data']['is_main'] = 1;//账号类型;0:子;1:主;
        }
        else {
            return ['code' => 1, 'msg' => '不存在的用户', 'data' => ''];
        }

        return $result;
    }

    //主账号登录
    static public function mainLogin($mobile, $code, $device, $miniCode, $bindId, $deviceId)
    {
        //比对用户输入的code和短信发送的code是否一致
        if(!Redis::exists($mobile.'_mobile_login')) {
            return ['code' => 1, 'msg' => '您输入的验证码无效，请重试', 'data' => ''];
        }
        else {
            if($code == Redis::get($mobile.'_mobile_login')) {//验证码一致
                $userInfo = AdminModel::select(
                    'admin.*',
                    'is_vip',
                )
                    ->where([
                        'username' => $mobile,
                        'parent_id' => 0,
                        'delete_flag' => 0
                    ])->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.id')->first();

                //用户不存在
                if(empty($userInfo)) {
                    $userId = self::register($mobile, $device, $miniCode, $bindId, $deviceId);
                    $userInfo = AdminModel::where('id', $userId)->first();
                }
                else if(!empty($userInfo)) {
                    $userId = $userInfo['id'];//子账号(账号类型为主账号时子账号同主账号)
                }
                if($userInfo['is_vip']>0 && $userInfo['invite_num'] < 3){
                    $userInfo['invite_num'] = 3;
                }
                $mainUserId = $userId;//主账号id

                if(Redis::exists('user_id_'.$userId.'_reset') && Redis::get('user_id_'.$userId.'_reset') == 1) {
                    Redis::del('user_id_'.$userId.'_reset');
                }

                if(Redis::GET('user_id_'.$userId.'_disabled') && Redis::GET('user_id_'.$userId.'_disabled') == 1) {
                    Redis::del('user_id_'.$userId.'_disabled');
                }

                $result = self::common([
                    'userId'=>$userId,
                    'mainUserId'=>$mainUserId,
                    'userType'=>0,//账号类型： 0-主 1-子
                    'type'=>$device,
                    'is_default_code' => 0,
                    'company_name' => $userInfo['company_name'],
                    'out_storage_way' => $userInfo['out_storage_way'],
                    'is_vip' => $userInfo['is_vip'],
                    'is_sync' => $userInfo['is_sync']
                ]);

//                $roleInfo = RoleSettingModel::where('role_id', $userInfo['admin_role'])->first();
//
//                $userFirstModuleArr = array_filter(explode(',', $roleInfo['first_module']), function($v) { return $v !== ''; });
//                $userSecondModuleArr = array_filter(explode(',', $roleInfo['second_module']), function($v) { return $v !== ''; });

//                $result['data']['nickname'] = $userInfo['nickname'];
//                $moduleInfo = self::moduleCommon($userFirstModuleArr, $userSecondModuleArr);

                $result['data']['parent_id'] = $userInfo['id'];
//                $result['data']['out_storage_way'] = $userInfo['out_storage_way'];
//                $result['data']['bind_id'] = $userInfo['bind_id'];
                $result['data']['is_sync'] = $userInfo['is_sync'];
//                $result['data']['invite_num'] = $userInfo['invite_num'];
//                $result['data']['invite_info'] = AdminService::inviteInfo($userInfo['bind_id']);
                $result['data']['is_main'] = 1;//账号类型;0:子;1:主;


                if($device == 3) {
                    $roleInfo = RoleSettingModel::where('role_id', $userInfo['admin_role'])->first();
                    $userFirstModuleArr = array_filter(explode(',', $roleInfo['first_module']), function($v) { return $v !== ''; });
                    $userSecondModuleArr = array_filter(explode(',', $roleInfo['second_module']), function($v) { return $v !== ''; });
                    $result['data']['nickname'] = $userInfo['nickname'];
                    $moduleInfo = self::moduleCommon($userFirstModuleArr, $userSecondModuleArr);
                    $result['data']['out_storage_way'] = $userInfo['out_storage_way'];
                    $result['data']['bind_id'] = $userInfo['bind_id'];
                    $result['data']['module_info'] = $moduleInfo;
                    $result['data']['is_bind_openid'] = empty($userInfo['openid'])?0:1;
                    $result['data']['is_vip'] = $userInfo['is_vip'];
                    $result['data']['invite_info'] = AdminService::inviteInfo($userInfo['bind_id']);
                    $result['data']['invite_num'] = $userInfo['invite_num'];
                }

                //字段权限列表
                $result['data']['field_list'] = DataFieldService::distinguishPermissionList($userInfo['id']);

                if(!empty($deviceId) && $deviceId != 'null' && $deviceId != null) {
                    AdminModel::where('id', $userId)->update([
                        'device_id' => $deviceId
                    ]);
                }

//                if($userInfo['is_sync'] == 0) {
//                    SyncDataController::syncMaterielCost($mainUserId, $userInfo['batch_title']);
//
//                    AdminModel::where('id', $mainUserId)->update(['is_sync' => 1]);
//                }

                $adminArray = json_decode(Redis::get('admin_array'), true);

                $key = array_search($userId, empty($adminArray)?[]:$adminArray);

                //主账号权限发生变动后重新登录取消权限不足的提示
                if($key !== false) {
                    unset($adminArray[$key]);
                    Redis::SETEX('admin_array', 86400*15, json_encode($adminArray));
                }

                Redis::del($mobile.'_mobile_login');//登录成功后销毁验证码

                self::loginLimit($userId, $result['data']['token'], $device);

                return $result;
            }
            else {
                return ['code' => 1, 'msg' => '您输入的验证码有误，请重新输入', 'data' => ''];
            }
        }
    }

    static public function pwdLogin($mobile,$pwd,$device,$minicode,$bindId,$deviceId)
    {
        $userInfo = AdminModel::select(
            'admin.*',
            'is_vip',
        )
            ->where([
                'username' => $mobile,
                'parent_id' => 0,
                'delete_flag' => 0
            ])->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.id')->first();

        //用户不存在
        if($userInfo['password'] != md5(md5($pwd.self::SALT))) {//验证用户密码
            return ['code' => 1, 'msg' => '您输入的密码有误，请重新输入', 'data' => ''];
        }
//        if(empty($userInfo)) {
//            $userId = self::register($mobile, $device, $minicode, $bindId, $deviceId);
//            $userInfo = AdminModel::where('id', $userId)->first();
//        }
//        else {
//            if($userInfo['password'] != md5(md5($pwd.self::SALT))) {//验证用户密码
//                return ['code' => 1, 'msg' => '您输入的密码有误，请重新输入', 'data' => ''];
//            }
//        }
        if($userInfo['is_vip'] > 0 && $userInfo['invite_num'] < 3){
            $userInfo['invite_num'] = 3;
        }
        $userId = $userInfo['id'];
        $mainUserId = $userId;//主账号id

        if(Redis::exists('user_id_'.$userId.'_reset') && Redis::get('user_id_'.$userId.'_reset') == 1) {
            Redis::del('user_id_'.$userId.'_reset');
        }

        if(Redis::GET('user_id_'.$userId.'_disabled') && Redis::GET('user_id_'.$userId.'_disabled') == 1) {
            Redis::del('user_id_'.$userId.'_disabled');
        }

        $result = self::common([
            'userId'=>$userId,
            'mainUserId'=>$mainUserId,
            'userType'=>0,//账号类型： 0-主 1-子
            'type'=>$device,
            'is_default_code' => 0,
            'company_name' => $userInfo['company_name'],
            'out_storage_way' => $userInfo['out_storage_way'],
            'is_vip' => $userInfo['is_vip'],
            'is_sync' => $userInfo['is_sync']
        ]);

        $result['data']['parent_id'] = $userInfo['id'];
        $result['data']['is_sync'] = $userInfo['is_sync'];
        $result['data']['is_main'] = 1;//账号类型;0:子;1:主;

        if($device == 3) {
            $roleInfo = RoleSettingModel::where('role_id', $userInfo['admin_role'])->first();

            $userFirstModuleArr = array_filter(explode(',', $roleInfo['first_module']), function($v) { return $v !== ''; });
            $userSecondModuleArr = array_filter(explode(',', $roleInfo['second_module']), function($v) { return $v !== ''; });

            $result['data']['nickname'] = $userInfo['nickname'];
            $moduleInfo = self::moduleCommon($userFirstModuleArr, $userSecondModuleArr);
            $result['data']['module_info'] = $moduleInfo;
            $result['data']['is_bind_openid'] = empty($userInfo['openid'])?0:1;
            $result['data']['is_vip'] = $userInfo['is_vip'];
            $result['data']['invite_info'] = AdminService::inviteInfo($userInfo['bind_id']);
            $result['data']['bind_id'] = $userInfo['bind_id'];
            $result['data']['invite_num'] = $userInfo['invite_num'];
            $result['data']['out_storage_way'] = $userInfo['out_storage_way'];
        }

//        字段权限列表
        $result['data']['field_list'] = DataFieldService::distinguishPermissionList($userInfo['id']);

//        if($userInfo['is_sync'] == 0) {
//            SyncDataController::syncMaterielCost($mainUserId, $userInfo['batch_title']);
//
//            AdminModel::where('id', $mainUserId)->update(['is_sync' => 1]);
//        }

        if(!empty($deviceId) && $deviceId != 'null' && $deviceId != null) {
            AdminModel::where('id', $userId)->update([
                'device_id' => $deviceId
            ]);
        }

        $adminArray = json_decode(Redis::get('admin_array'), true);

        $key = array_search($userId, empty($adminArray)?[]:$adminArray);

        //主账号权限发生变动后重新登录取消权限不足的提示
        if($key !== false) {
            unset($adminArray[$key]);
            Redis::SETEX('admin_array', 86400*15, json_encode($adminArray));
        }

        Redis::del($mobile.'_mobile_login');//登录成功后销毁验证码

        self::loginLimit($userId, $result['data']['token'], $device);

        return $result;
    }

    //新登录-变更日期2022-08-10
    static public function userLogin($username, $password, $device, $deviceId, $minicode)
    {
        $userInfo = AdminModel::select(
            'admin.*',
            'is_vip',
            'c.batch_title'
        )
            ->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.parent_id')
            ->leftJoin('admin as c', 'c.id', '=', 'admin.parent_id')
            ->where([
                'admin.username' => $username,
                'admin.newpwd' => substr($password, -6),
                'admin.delete_flag' => 0
            ])
            ->where('admin.parent_id', '!=', 0)
            ->first();

        if(empty($userInfo)) {
            return ['code' => 1, 'msg' => '用户不存在或密码错误，请重试', 'data' => ''];
        }

        if(!$userInfo['is_active']) {
            return ['code' => 1, 'msg' => '当前账号已被禁用，请联系主账号管理员', 'data' => ''];
        }

        $adminInfo = AdminModel::where('id', $userInfo['parent_id'])->first();

        if($userInfo['batch_title'].$userInfo['newpwd'] == $password) {//验证用户密码
            $result = self::common([
                'userId'=>$userInfo['id'],
                'mainUserId'=>$userInfo['parent_id'],
                'userType'=>1,//账号类型： 0-主 1-子
                'type'=>$device,
                'is_default_code' => 0,
                'company_name' => $userInfo['company_name'],
                'out_storage_way' => $userInfo['out_storage_way'],
                'is_vip' => $userInfo['is_vip'],
                'is_sync' => $adminInfo['is_sync']
            ]);

            if(!empty($deviceId) && $deviceId != 'null' && $deviceId != null) {
                AdminModel::where('id', $userInfo['id'])->update([
                    'device_id' => $deviceId
                ]);
            }

            $mainInfo = AdminModel::where('id', $userInfo['parent_id'])->first();
            $result['data']['parent_id'] = $userInfo['parent_id'];
            $result['data']['is_sync'] = $mainInfo['is_sync'];
            $result['data']['is_main'] = 0;//账号类型;0:子;1:主;

            if($userInfo['is_vip'] > 0 && $mainInfo['invite_num'] < 3){
                $userInfo['invite_num'] = 3;
                $mainInfo['invite_num'] = 3;
            }
            if($device == 3) {
                $userFirstModuleArr = array_filter(explode(',', $userInfo['first_module']), function($v) { return $v !== ''; });
                $userSecondModuleArr = array_filter(explode(',', $userInfo['second_module']), function($v) { return $v !== ''; });

                $moduleInfo = self::moduleCommon($userFirstModuleArr, $userSecondModuleArr);
                $result['data']['invite_num'] = $mainInfo['invite_num'];
                $result['data']['company_name'] = $mainInfo['company_name'];
                $result['data']['bind_id'] = $mainInfo['bind_id'];
                $result['data']['invite_info'] = AdminService::inviteInfo($mainInfo['id']);
                $result['data']['is_default_pwd'] = $userInfo['is_default_pwd'];
                $result['data']['out_storage_way'] = $userInfo['out_storage_way'];
                $result['data']['nickname'] = $userInfo['nickname'];
                $result['data']['module_info'] = $moduleInfo;
                $result['data']['is_bind_openid'] = empty($userInfo['openid'])?0:1;
                $result['data']['is_vip'] = $userInfo['is_vip'];
            }

            //字段权限列表
            $result['data']['field_list'] = DataFieldService::distinguishPermissionList($userInfo['id']);

            if(Redis::exists('user_id_'.$userInfo['id'].'_disabled') && Redis::get('user_id_'.$userInfo['id'].'_disabled') == 1) {
                Redis::del('user_id_'.$userInfo['id'].'_disabled');
            }

//            if($mainInfo['is_sync'] == 0) {
//                SyncDataController::syncMaterielCost($userInfo['parent_id'], $userInfo['batch_title']);
//
//                AdminModel::where('id', $userInfo['parent_id'])
//                    ->update(['is_sync' => 1]);
//            }

            self::loginLimit($userInfo['id'], $result['data']['token'], $device);

            if(Redis::exists('user_id_'.$userInfo['id'].'_reset') && Redis::get('user_id_'.$userInfo['id'].'_reset') == 1) {
                Redis::del('user_id_'.$userInfo['id'].'_reset');
            }

            return $result;
        }
        else {
            return ['code' => 1, 'msg' => '密码错误', 'data' => ''];
        }
    }

    //子账号登录
    static public function userLogin1($username, $password, $device, $deviceId, $minicode)
    {
        $userInfo = AdminModel::select(
            'admin.*',
            'is_vip',
        )
            ->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.parent_id')
            ->where([
                'username' => $username,
                'delete_flag' => 0
            ])
            ->where('parent_id', '!=', 0)
            ->first();

        if(empty($userInfo)) {
            return ['code' => 1, 'msg' => '用户不存在', 'data' => ''];
        }

        if(!$userInfo['is_active']) {
            return ['code' => 1, 'msg' => '当前账号已被禁用，请联系主账号管理员', 'data' => ''];
        }

        if($userInfo['password'] == md5(md5($password.self::SALT))) {//验证用户密码
            $result = self::common([
                'userId'=>$userInfo['id'],
                'mainUserId'=>$userInfo['parent_id'],
                'userType'=>1,//账号类型： 0-主 1-子
                'type'=>$device,
                'is_default_code' => 0,
                'company_name' => $userInfo['company_name'],
                'out_storage_way' => $userInfo['out_storage_way'],
                'is_vip' => $userInfo['is_vip'],
            ]);

            $userFirstModuleArr = array_filter(explode(',', $userInfo['first_module']), function($v) { return $v !== ''; });
            $userSecondModuleArr = array_filter(explode(',', $userInfo['second_module']), function($v) { return $v !== ''; });

            $moduleInfo = self::moduleCommon($userFirstModuleArr, $userSecondModuleArr);

            if(!empty($deviceId) && $deviceId != 'null' && $deviceId != null) {
                AdminModel::where('id', $userInfo['id'])->update([
                    'device_id' => $deviceId
                ]);
            }

            $mainInfo = AdminModel::where('id', $userInfo['parent_id'])->first();
            $result['data']['invite_num'] = $mainInfo['invite_num'];
            $result['data']['company_name'] = $mainInfo['company_name'];
            $result['data']['parent_id'] = $userInfo['parent_id'];
            $result['data']['is_sync'] = $mainInfo['is_sync'];
            $result['data']['bind_id'] = $mainInfo['bind_id'];
            $result['data']['invite_info'] = AdminService::inviteInfo($mainInfo['id']);
            $result['data']['is_default_pwd'] = $userInfo['is_default_pwd'];
            $result['data']['out_storage_way'] = $userInfo['out_storage_way'];
            $result['data']['is_main'] = 0;//账号类型;0:子;1:主;
            $result['data']['nickname'] = $userInfo['nickname'];
            $result['data']['module_info'] = $moduleInfo;
            $result['data']['is_bind_openid'] = empty($userInfo['openid'])?0:1;
            $result['data']['is_vip'] = $userInfo['is_vip'];

            //字段权限列表
            $result['data']['field_list'] = DataFieldService::distinguishPermissionList($userInfo['id']);

            if(Redis::exists('user_id_'.$userInfo['id'].'_disabled') && Redis::get('user_id_'.$userInfo['id'].'_disabled') == 1) {
                Redis::del('user_id_'.$userInfo['id'].'_disabled');
            }

//            if($mainInfo['is_sync'] == 0) {
//                SyncDataController::syncMaterielCost($userInfo['parent_id'], $userInfo['batch_title']);
//
//                AdminModel::where('id', $userInfo['parent_id'])
//                    ->update(['is_sync' => 1]);
//            }

            self::loginLimit($userInfo['id'], $result['data']['token'], $device);

            if(Redis::exists('user_id_'.$userInfo['id'].'_reset') && Redis::get('user_id_'.$userInfo['id'].'_reset') == 1) {
                Redis::del('user_id_'.$userInfo['id'].'_reset');
            }

            return $result;
        }
        else {
            return ['code' => 1, 'msg' => '密码错误', 'data' => ''];
        }
    }

    /**
     *
     * @param $userId 用户id
     * @param $mainUserId 主账号id
     * @param $userType 账号类型： 0-主 1-子
     * @param $device 设备类型
     * @param $companyName 公司名称
     * @param $isDefaultCode 是否默认验证码登陆
     * AUTHOR  : Sun Wu
     * DateTime: 2022/2/24 13:51
     * @return array
     */
    static private function common($arr)
    {
        $publicKey = SystemConfigModel::getConfigValue('public');
        $token = DBRSAUtil::rsaEncrypt(json_encode($arr), $publicKey);

        // //登录过期设置（15天）
        Redis::SETEX('user_id_'.$arr['userId'].'_'.$arr['type'], 86400*15, $arr['userId']);

        AdminModel::where('id', $arr['userId'])->update(['device' => $arr['type']]);

        if($arr['type'] == 3) {
            $returnData = [
                'user_id' => $arr['userId'],
                'token' => $token,
                'company_name' => empty($arr['company_name'])?'':$arr['company_name']
            ];
        }
        else {
            $returnData = [
                'user_id' => $arr['userId'],
                'token' => $token,
            ];
        }

        MaterielClassService::createdDefaultProductWarehouse($arr['mainUserId']);
        StorageService::createDefaultProductStorage($arr['mainUserId']);

        if(!$arr['is_sync']) {
            self::deleteMultiStorageManageInfo($arr['mainUserId']);
            self::resetStorageAndSerial($arr['mainUserId']);
        }

        AdminModel::where('id', $arr['mainUserId'])->update(['is_sync' => 1]);
        return [
            'code' => 0,
            'msg' => 'success',
            'data' => $returnData
        ];
    }

    //注册
    static protected function register($mobile, $device, $miniCode, $bindId, $deviceId)
    {
        $arr['username'] = $mobile;
        $arr['mobile'] = $mobile;
        $arr['created_at'] = time();
        $arr['device'] = $device;
        $arr['bind_id'] = $bindId;

        if(!empty($deviceId)) {
            $arr['device_id'] = $deviceId;
        }

        if(!empty($miniCode)) {
            $result = json_decode(self::getOpenId($miniCode), true);
            $arr['openid'] = $result['openid'];
        }

        $insertId = AdminModel::insertGetId($arr);

        $vipInfo = VipSettingModel::where('id', 1)->first();

        AdminAddendumModel::insert([
            'main_id' => $insertId,
            'album_amount' => $vipInfo['album_amount'],
            'album_page_amount' => $vipInfo['album_page_amount'],
            'empty_bill_amount' => $vipInfo['empty_bill_amount'],
            'special_seal' => $vipInfo['special_seal'],
            'one_key_album_times' => $vipInfo['one_key_album_times'],
            'express_check_times' => $vipInfo['express_check_times'],
            'account_storage' => $vipInfo['account_storage'],
            'clear_watermark_or_not' => $vipInfo['clear_watermark_or_not'],
            'sub_account_number' => $vipInfo['sub_account_number'],
        ]);

        $checkInfo = AdminModel::where('id', $bindId)->first();
        if(!empty($checkInfo)) {
            AdminModel::where('id', $bindId)->increment('invite_num');
        }

        return $insertId;
    }

    static public function moduleCommon($firstModule, $secondModule)
    {
        $firstModuleInfo = ModuleModel::select(
            'id',
            'module_name',
            'upper_module_id',
            'module_img',
            'type',
            'sort',
            'icon',
            'url1',
            'url2'
        )
            ->whereIn('id', $firstModule)
            ->where('delete_flag', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'DESC')
            ->get()->toArray();

        $secondModuleInfo = ModuleModel::select(
            'id',
            'module_name',
            'upper_module_id',
            'module_img',
            'type',
            'sort',
            'icon',
            'url1',
            'url2'
        )
            ->whereIn('id', $secondModule)
            ->where('delete_flag', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'DESC')
            ->get()->toArray();

        foreach($firstModuleInfo as $key => $value) {
            foreach($secondModuleInfo as $k => $v) {
                if($value['id'] == $v['upper_module_id']) {
                    $firstModuleInfo[$key]['second_module'][] = $v;
                }
            }
        }

        return $firstModuleInfo;
    }

    static public function getOpenId($code)
    {
        $curl = curl_init();

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".
            config('app.miniapp_id')."&secret=".
            config('app.miniapp_secret')."&js_code=".$code."&grant_type=authorization_code";

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    static public function loginLimit($userId, $token, $device)
    {
        if(in_array($device, [1,2,4,5])) {
            Redis::SETEX($userId.'_app', 86400*15, $token);
        }
        else {
            Redis::SETEX($userId.'_pc', 86400*15, $token);
        }

        return true;
    }

    //重置库存和序列号
    public function resetStorageAndSerial($mainUserId)
    {
        //获取直接入库未被撤销的序列号信息
        $assignInSerial = self::getInSerialData($mainUserId);

        if(empty($assignInSerial)) {
            return true;
        }

        //获取直接出库未被撤销的序列号信息
        $assignOutSerial = self::getOutSerialData($mainUserId);

        //获得出入库不重复的序列号id
        $arr = array_merge(array_diff($assignInSerial, $assignOutSerial), array_diff($assignOutSerial, $assignInSerial));

        //获取该账号下所有序列号
        $accountSerial = StorageManageModel::select('b.id', 'storage_manage.main_id')
            ->leftJoin('serial_number as b', 'b.storage_manage_id', '=', 'storage_manage.id')
            ->where('storage_manage.main_id', $mainUserId)->get()->toArray();

        $accountSerialArr = [];
        foreach($accountSerial as $val) {
            if(isset($val['id'])) {
                $accountSerialArr[] = $val['id'];
            }
        }

        //账号下所有序列号id和出入库不重复的序列号id的差集
        $rightSerial = array_merge(array_diff($arr, $accountSerialArr), array_diff($accountSerialArr, $arr));

        DB::beginTransaction();

        try {
            DB::enableQueryLog();
            StorageManageModel::from('storage_manage as a')
                ->leftJoin('serial_number as b', 'b.storage_manage_id', '=', 'a.id')
                ->where('a.main_id', $mainUserId)
                ->whereIn('b.id', $rightSerial)
                ->update([
                    'status' => 0
                ]);


            StorageManageModel::from('storage_manage as a')
                ->leftJoin('serial_number as b', 'b.storage_manage_id', '=', 'a.id')
                ->where('a.main_id', $mainUserId)
                ->whereNotIn('b.id', $rightSerial)
                ->update([
                    'status' => 1
                ]);

            $storageManageInfo = DB::select('
                SELECT storage_manage_id,count(*) AS c
                    FROM s_storage_manage AS a LEFT JOIN
                        s_serial_number AS b
                    ON a.id = b.storage_manage_id
                WHERE a.main_id = '.$mainUserId.' AND b.status = 1
                    GROUP BY b.storage_manage_id having c >= 1
            ');

            $storageManageEmpty = [];
            $storageManageUpdate = [];
            foreach($storageManageInfo as $v) {
                $storageManageEmpty[] = $v->storage_manage_id;

                $storageManageUpdate[] = [
                    'id' => $v->storage_manage_id,
                    'in_storage_num' => $v->c,
                    'virtual_storage_num' => $v->c,
                ];
            }

            if(!empty($storageManageUpdate)) {
                batch()->update(new StorageManageModel, $storageManageUpdate, 'id');
            }

//            if(!empty($storageManageEmpty)) {
//                StorageManageModel::where('main_id', $mainUserId)->whereNotIn('id', $storageManageEmpty)
//                    ->update([
//                        'in_storage_num' => 0,
//                        'virtual_storage_num' => 0,
//                    ]);
//            }

            DB::commit();
            return true;
        }
        catch(\Exception $e) {
            Log::debug('同步序列号信息失败');
            DB::rollBack();
            return false;
        }
    }

    private function getOutSerialData($mainUserId)
    {
        //获取未被撤销的入库序列号信息
        $logOutCancelInfo = LogOutStorageModel::where([
            'main_id' => $mainUserId,
            'type' => 2,
            'is_cancel' => 0
        ])
            ->get()->toArray();

        if(empty($logOutCancelInfo)) {
            return true;
        }

        $createTime = [];
        foreach($logOutCancelInfo as $value) {
            $createTime[] = strtotime($value['created_at']);
            $createTime[] = strtotime($value['created_at']) - 1;
            $createTime[] = strtotime($value['created_at']) - 2;
        }

        //已撤销的序列号信息
        $operateLog = OperationLogModel::where(
            'remark', '直接出库'
        )
            ->where('data', 'like', '%'.'serial_no'.'%')
            ->whereIn('created_at', $createTime)->get()->toArray();

        $outSerialData = [];
        foreach($operateLog as $val) {
            $dataContent = json_decode($val['data'], 'true');
            if(!empty($dataContent['goods_info'])) {
                $goodsInfo = json_decode($dataContent['goods_info'], true);
                foreach($goodsInfo as $v) {
                    if(!empty($v['serial_no'])) {
                        $storageManageInfo = StorageManageModel::where('id', $v['storageManageId'])->first();

                        $serialArr = array_filter(explode(',', $v['serial_no']), function($v) { return $v !== ''; });

                        $getSerailArr = [];
                        foreach($serialArr as $v1) {
                            $getSerailArr[] = $v1;
                        }

                        $serialInfo = SerialNumberModel::where([
                            'goods_id' => $storageManageInfo['type_id']
                        ])
                            ->whereIn('serial_no', $getSerailArr)->get()->toArray();

                        foreach($serialInfo as $v1) {
                            $outSerialData[] = $v1['id'];
                        }
                    }
                }
            }
        }

        return $outSerialData;
    }

    private function getInSerialData($mainUserId)
    {
        //获取未被撤销的入库序列号信息
        $logInCancelInfo = LogInStorageModel::where([
            'main_id' => $mainUserId,
            'type' => 2,
            'is_cancel' => 0
        ])
            ->get()->toArray();

        if(empty($logInCancelInfo)) {
            return [];
        }

        $createTime = [];
        foreach($logInCancelInfo as $value) {
            $createTime[] = strtotime($value['created_at']);
            $createTime[] = strtotime($value['created_at']) - 1;
            $createTime[] = strtotime($value['created_at']) - 2;
        }

        //獲取新建入庫的操作日誌
        $operateLog = OperationLogModel::where(
            'remark', '新建直接入库'
        )
            ->where('data', 'like', '%'.'serial_no'.'%')
            ->whereIn('created_at', $createTime)->get()->toArray();

        $inSerialData = [];
        foreach($operateLog as $val) {
            $dataContent = json_decode($val['data'], 'true');
            if(!empty($dataContent['goods_info'])) {
                $goodsInfo = json_decode($dataContent['goods_info'], true);
                foreach($goodsInfo as $v) {
                    if(!empty($v['serial_no'])) {

                        $serialArr = array_filter(explode(',', $v['serial_no']), function($v) { return $v !== ''; });

                        $getSerailArr = [];
                        foreach($serialArr as $v1) {
                            $getSerailArr[] = $v1;
                        }

                        $serialInfo = SerialNumberModel::whereIn('serial_no', $getSerailArr)->get()->toArray();

                        foreach($serialInfo as $v1) {
                            $inSerialData[] = $v1['id'];
                        }
                    }
                }
            }
        }

        return $inSerialData;
    }


    private static function deleteMultiStorageManageInfo($mainUserId)
    {
        $storageManageInfo = DB::select('
            select id,type_id,`storage_id`,`location_id`,count(*) as c
                from s_storage_manage
                    where delete_flag = 0 and main_id = '.$mainUserId.'
                        group by type_id, location_id having c > 1
        ');

        if(empty($storageManageInfo)) {
            return true;
        }

        $storageManageId = [];//被删除的库存id
        $updateStorageMangeInfo = [];//被更新的目标库存信息
        $inLogInfo = [];//要被重置的入库记录
        $outLogInfo = [];//要被重置的出库记录
        $serialInfo = [];//要被重置的序列号
        foreach($storageManageInfo as $value) {
            $getStorageManageInfo = StorageManageModel::where([
                'type_id' => $value->type_id,
                'storage_id' => $value->storage_id,
                'delete_flag' => 0
            ])
                ->orderBy('in_storage_num', 'desc')
                ->get()->toArray();

            $num = 0;
            foreach($getStorageManageInfo as $k => $val) {
                if($k != 0) {
                    $storageManageId[] = $val['id'];
                    $num += $val['in_storage_num'];

                    //要被重置的入库记录
                    $resetLogInfo = LogInStorageModel::where([
                        'curr_storage_manage_id' => $val['id'],
                        'delete_flag' => 0
                    ])->get()->toArray();

                    foreach($resetLogInfo as $v) {
                        $inLogInfo[] = [
                            'id' => $v['id'],
                            'curr_storage_manage_id' => $getStorageManageInfo[0]['id'],
                            'old_in_storage_manage_id' => $v['curr_storage_manage_id'],
                        ];
                    }

                    //要被重置的出库记录
                    $resetLogInfo = LogOutStorageModel::where([
                        'curr_storage_manage_id' => $val['id'],
                        'delete_flag' => 0
                    ])->get()->toArray();

                    foreach($resetLogInfo as $v1) {
                        $outLogInfo[] = [
                            'id' => $v1['id'],
                            'curr_storage_manage_id' => $getStorageManageInfo[0]['id'],
                            'old_in_storage_manage_id' => $v1['curr_storage_manage_id'],
                        ];
                    }

                    //要被重置的序列号记录
                    $resetSerialInfo = SerialNumberModel::where([
                        'storage_manage_id' => $val['id'],
                    ])->get()->toArray();

                    foreach($resetSerialInfo as $v2) {
                        $serialInfo[] = [
                            'id' => $v2['id'],
                            'storage_manage_id' => $getStorageManageInfo[0]['id'],
                            'old_serial_storage_manage_id' => $v2['storage_manage_id'],
                        ];
                    }
                }
            }
            $updateStorageMangeInfo[] = [
                'id' => $getStorageManageInfo[0]['id'],
                'in_storage_num' => $getStorageManageInfo[0]['in_storage_num'] + $num,
                'virtual_storage_num' => $getStorageManageInfo[0]['virtual_storage_num'] + $num,
            ];
        }

        $storageManageId = array_values(array_unique($storageManageId));

        if(empty($storageManageId)) {
            return true;
        }

        DB::beginTransaction();

        try {
            $operateLogArr = [];
            StorageManageModel::whereIn('id', $storageManageId)->update([
                'delete_flag' => 1
            ]);

            $operateLogArr[] = [
                'main_id' => $mainUserId,
                'user_id' => $mainUserId,
                'remark' => '删除重复库存信息',
                'data' => json_encode($storageManageId),
                'created_at' => time(),
                'delete_flag' => 1,
                'ip' => $_SERVER["REMOTE_ADDR"]
            ];

            if(!empty($updateStorageMangeInfo)) {
                batch()->update(new StorageManageModel, $updateStorageMangeInfo, 'id');
            }

            if(!empty($inLogInfo)) {
                $newInLogInfo = [];
                foreach($inLogInfo as $v3) {
                    $newInLogInfo[] = [
                        'id' => $v3['id'],
                        'curr_storage_manage_id' => $v3['curr_storage_manage_id']
                    ];
                }

                batch()->update(new LogInStorageModel, $newInLogInfo,'id');

                $operateLogArr[] = [
                    'main_id' => $mainUserId,
                    'user_id' => $mainUserId,
                    'remark' => '删除重复入库信息',
                    'data' => json_encode($inLogInfo),
                    'created_at' => time(),
                    'delete_flag' => 1,
                    'ip' => $_SERVER["REMOTE_ADDR"]
                ];
            }

            if(!empty($outLogInfo)) {
                $newOutLogInfo = [];
                foreach($outLogInfo as $v4) {
                    $newOutLogInfo[] = [
                        'id' => $v4['id'],
                        'curr_storage_manage_id' => $v4['curr_storage_manage_id']
                    ];
                }

                batch()->update(new LogOutStorageModel, $newOutLogInfo, 'id');

                $operateLogArr[] = [
                    'main_id' => $mainUserId,
                    'user_id' => $mainUserId,
                    'remark' => '删除重复出库信息',
                    'data' => json_encode($outLogInfo),
                    'created_at' => time(),
                    'delete_flag' => 1,
                    'ip' => $_SERVER["REMOTE_ADDR"]
                ];
            }

            if(!empty($serialInfo)) {
                $newSerialStorage = [];
                foreach($serialInfo as $v5) {
                    $newSerialStorage[] = [
                        'id' => $v5['id'],
                        'storage_manage_id' => $v5['storage_manage_id']
                    ];
                }
                batch()->update(new SerialNumberModel, $newSerialStorage, 'id');

                $operateLogArr[] = [
                    'main_id' => $mainUserId,
                    'user_id' => $mainUserId,
                    'remark' => '删除重复序列号信息信息',
                    'data' => json_encode($serialInfo),
                    'created_at' => time(),
                    'delete_flag' => 1,
                    'ip' => $_SERVER["REMOTE_ADDR"]
                ];
            }

            OperationLogModel::insert($operateLogArr);
            DB::commit();
            return true;
        }
        catch(\Exception $e) {
            DB::rollBack();
            Log::debug('删除重复库存出错:'.var_export($e->getMessage(), true));
            return false;
        }
    }
}
